package com.example.databindingdemo;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.databindingdemo.databinding.ItemBinding;
import com.example.databindingdemo.model.Book;

import java.util.List;

/**
 * @author: tuyrt7 on 2020/9/8.
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<Book> mBookList;

    public MyAdapter(List<Book> bookList) {
        mBookList = bookList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemBinding binding = ItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Book book = mBookList.get(position);
        holder.bindData(book);
    }

    @Override
    public int getItemCount() {
        return mBookList == null ? 0 : mBookList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ItemBinding mBinding;

        public ViewHolder(@NonNull ItemBinding binding) {
            super(binding.getRoot());
            mBinding = binding;
        }

        public void bindData(Book book) {
            mBinding.setBook(book);
        }
    }
}
